import { Component, v3, _decorator } from 'cc';
import Joystick from '../../../common/components/Joystick';
import TargetCamera from '../../../common/components/TargetCamera';
import Player from '../../components/Player';
import GameMap from './GameMap';

const { ccclass, property } = _decorator;

/** 游戏逻辑事件 */
export enum GamePlayEventType {
	GameOver = 'event_game_over'
}

/** 玩家游戏数据 */
export interface PlayerData {
	level: number; // 玩家等级
	playTime: number; // 游戏耗时
}

@ccclass('GamePlay')
export class GamePlay extends Component {
	@property(GameMap)
	map: GameMap = null;

	@property(Player)
	player: Player = null;

	@property(TargetCamera)
	camera: TargetCamera = null;

	private joystick: Joystick;
	private playerObj: PlayerData;

	// 原子类型可以不用声明类型，编译器会自行推断
	private isPlaying = false;

	start() {
		this.joystick = this.getComponent(Joystick);
		this.player.setBoundary(this.map.getBoundary());
	}

	public startGame() {
		// 初始化玩家数据
		this.playerObj = { level: 1, playTime: Date.now() };

		// 延迟执行
		this.scheduleOnce(() => {
			this.map.generateMap();
			this.player.setPosition(v3(0, 0, 0));
			this.camera.capture();
			this.isPlaying = true;
		});

		// FIXME: 测试游戏结束
		this.scheduleOnce(() => {
			this.gameOver();
		}, 10);
	}

	private gameOver() {
		this.isPlaying = false;
		this.player.setInput(null);
		this.playerObj.playTime = Math.ceil((Date.now() - this.playerObj.playTime) / 1000);
		this.node.emit(GamePlayEventType.GameOver, this.playerObj);
	}

	update(dt: number) {
		if (!this.isPlaying) return;

		const input: any = this.joystick.getInput();
		if (input) {
			this.player.setInput(input);
		}
	}
}
